package cn.com.anypay.manager.service.impl;

import cn.com.anypay.manager.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务实现类
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    
    private final Random random = new Random();
    
    /**
     * 生成验证码
     */
    @Override
    public String generateCode(String type, String key) {
        // 生成6位随机验证码
        int code = 100000 + random.nextInt(900000);
        String codeStr = String.valueOf(code);
        
        // 保存到Redis，默认60秒过期
        saveCode(type, key, codeStr, 60);
        
        return codeStr;
    }
    
    /**
     * 验证验证码
     */
    @Override
    public boolean verifyCode(String type, String key, String code) {
        String storedCode = getCode(type, key);
        
        // 验证码不存在或已过期
        if (storedCode == null) {
            return false;
        }
        
        // 验证码匹配
        boolean isValid = storedCode.equals(code);
        
        // 验证成功后删除验证码，防止重复使用
        if (isValid) {
            deleteCode(type, key);
        }
        
        return isValid;
    }
    
    /**
     * 保存验证码
     */
    @Override
    public void saveCode(String type, String key, String code, int expireSeconds) {
        String redisKey = buildRedisKey(type, key);
        redisTemplate.opsForValue().set(redisKey, code, expireSeconds, TimeUnit.SECONDS);
    }
    
    /**
     * 获取验证码
     */
    @Override
    public String getCode(String type, String key) {
        String redisKey = buildRedisKey(type, key);
        return redisTemplate.opsForValue().get(redisKey);
    }
    
    /**
     * 删除验证码
     */
    @Override
    public void deleteCode(String type, String key) {
        String redisKey = buildRedisKey(type, key);
        redisTemplate.delete(redisKey);
    }
    
    /**
     * 构建Redis键
     */
    private String buildRedisKey(String type, String key) {
        return "verification:code:" + type + ":" + key;
    }
}